<template>
  <div class="UOL_box">
    <div class="title">
      <span
        v-for="item in ['待支付', '已过期', '已支付']"
        :key="item"
        :class="active == item ? 'active' : ''"
        @click="handleTab(item)"
        >{{ item }}</span
      >
    </div>
    <div class="list" v-if="newTodayList.length != 0">
      <van-swipe-cell v-for="item in newTodayList" :key="item.menu_id">
        <div>
          <UserListItem :foodItem="item" :isSPay="active" />
        </div>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="cancelOrdering(item.menu_id)"
          />
        </template>
      </van-swipe-cell>
      <!--提交栏-->
      <div class="subOder" v-if="active == '待支付'">
        <van-submit-bar
          :price="totalValue * 100"
          button-text="提交订单"
          @submit="onSubmit"
        >
        </van-submit-bar>
      </div>
    </div>
    <!--空状态-->
    <div v-else>
      <van-empty :description="`未有${active}菜品`" />
    </div>
    <!--支付弹出框-->
    <div class="payBox" v-if="payShow">
      <van-dialog
        v-model:show="payDialog"
        title="标题"
        show-cancel-button
        @confirm="payConfirm"
      >
        <!-- 密码输入框 -->
        <van-password-input
          :value="passwValue"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
      </van-dialog>
      <!-- 数字键盘 -->
      <van-number-keyboard
        v-model="passwValue"
        :show="showKeyboard"
        @blur="showKeyboard = false"
      />
    </div>
  </div>
</template>

<script>
import { provide, ref, watchEffect } from "vue";
import { Toast } from "vant";
import { useStore } from "vuex";
import {
  getOrderCancel,
  getOrderClose,
  getOrderUser,
} from "../../../api/ordering";
import UserListItem from "./UserListItem";
import { getLogin } from "../../../api/user";
export default {
  name: "UserOrderingList",
  components: { UserListItem },
  setup() {
    const store = useStore();
    //支付框
    const payShow = ref(false); //弹出框
    const payDialog = ref(true);
    const passwValue = ref(""); //密码输入值
    const showKeyboard = ref(true); //数组键盘
    //tab类型
    const active = ref("待支付");
    //总值
    const totalValue = ref(0);
    //时间点
    const time = new Date().getHours();
    //所处时间段（早中晚）
    const timeType = ref("早");
    //数据
    const todayList = ref([]);
    const newTodayList = ref([]); //代理数据集
    const stayPayList = ref([]); //待支付
    const yetPayList = ref([]); //已支付
    const overDueList = ref([]); //已过期
    //获取用户订单菜品
    let handleGetOrderUser = () => {
      getOrderUser(store.state.user.profile.user_id).then((res) => {
        // console.log(res);
        stayPayList.value = todayList.value = res.data || [];
      });
    };
    handleGetOrderUser();
    //根据时间点筛选菜品（早中晚）
    watchEffect(() => {
      if (6 <= time && time <= 7) {
        timeType.value = "早";
        stayPayList.value = todayList.value?.filter(
          (item) => item.menu_type == "早" && item.order_status == "false"
        );
      } else if (11 <= time && time <= 13) {
        timeType.value = "中";
        stayPayList.value = todayList.value?.filter(
          (item) => item.menu_type == "中" && item.order_status == "false"
        );
      } else if (18 <= time && time <= 19) {
        timeType.value = "晚";
        stayPayList.value = todayList.value?.filter(
          (item) => item.menu_type == "晚" && item.order_status == "false"
        );
      } else {
        stayPayList.value = [];
      }
      //开始为待支付
      newTodayList.value = stayPayList.value;
      //总值
      totalValue.value = 0;
      stayPayList.value?.forEach((item) => {
        totalValue.value += Number(item.menu_price) * item.order_count;
      });
    });

    store.commit("user/handleOrderingCount", stayPayList.value.length);

    //菜品数量变化 重新结算值
    const toUser = () => {
      handleGetOrderUser();
      handleGetOrderUser();
    };
    provide("toUser", toUser);

    //切换类型
    const handleTab = (value) => {
      active.value = value;
      //待支付
      if (value == "待支付") {
        newTodayList.value = stayPayList.value;
        Toast("今日待支付菜品");
      }
      //已支付
      else if (value == "已支付") {
        Toast("今日已支付菜品");
        yetPayList.value = todayList.value.filter(
          (item) => item.order_status == "true"
        );
        newTodayList.value = yetPayList.value || [];
        // console.log(yetPayList.value);
      }
      //已过期
      else if (value == "已过期") {
        Toast("今日已过期菜品");
        todayList.value?.filter((item) => {
          if (
            item.menu_type == "早" &&
            item.order_status == "false" &&
            time > 7
          ) {
            overDueList.value.push(item);
          } else if (
            item.menu_type == "中" &&
            item.order_status == "false" &&
            time > 13
          ) {
            overDueList.value.push(item);
          } else if (
            item.menu_type == "晚" &&
            item.order_status == "false" &&
            time > 19
          ) {
            overDueList.value.push(item);
          } else {
            overDueList.value = [];
          }
        });
        newTodayList.value = Array.from(new Set(overDueList.value));
      }
    };
    // console.log(active.value);
    //删除订单
    const cancelOrdering = (menu_id) => {
      let obj = {
        user_id: store.state.user.profile.user_id,
        menu_id,
        cancelValue: "all",
      };
      getOrderCancel(obj).then((res) => {
        if (res.status == 200) {
          handleTab(active.value);
          handleGetOrderUser();
          Toast("删除成功");
        }
      });
    };

    //提交订单
    const onSubmit = () => {
      //打开支付弹出框
      payShow.value = true;
    };
    //确认支付
    const payConfirm = () => {
      //登录信息
      const loginMag = {
        user_name: store.state.user.profile.user_name,
        user_password: passwValue.value,
      };
      //支付信息
      const obj = {
        user_id: store.state.user.profile.user_id,
        total: -totalValue.value,
        type: timeType.value,
      };
      //登录请求
      getLogin(loginMag).then((res) => {
        // console.log(res);
        if (res.status == 200) {
          //支付请求
          getOrderClose(obj).then((res) => {
            if (res.status == 200) {
              // 再次登录获取零钱信息
              getLogin(loginMag).then((res) => {
                store.commit("user/setUser", res.data);
                store.commit("user/setToken", res.token);
              });
              handleGetOrderUser();
              Toast(res.message);
            }
          });
        } else {
          Toast("密码错误");
        }
      });
      //关闭支付弹出框
      payShow.value = false;
    };
    return {
      payShow,
      payDialog,
      passwValue,
      showKeyboard,
      totalValue,
      onSubmit,
      payConfirm,
      store,
      active,
      newTodayList,
      handleTab,
      cancelOrdering,
    };
  },
};
</script>

<style scoped lang="less">
.UOL_box {
  position: relative;
  flex: auto;
  width: 97%;
  margin: 0 auto;
  border-radius: 0.5rem;
  background-color: #fff;
  padding: 0 0.4rem;
  overflow: hidden;
  box-sizing: border-box;
  .title {
    width: 100%;
    padding: 0.5rem 0;
    span {
      color: #646566;
      font-size: 1.05rem;
      padding: 0.2rem 0.4rem;
      margin: 0 0.5rem;
    }
    .active {
      border-bottom: 2px solid #ff8917;
    }
  }
  .list {
    height: 100%;
    overflow-y: scroll;
    padding-bottom: 8rem;
    box-sizing: border-box;
    .delete-button {
      height: 100%;
    }
    .subOder {
      width: 80%;
      transform: translate(50%);
      position: absolute;
      bottom: 2rem;
      right: 50%;
      .van-button {
        width: 10rem;
      }
    }
  }
}
:deep(.van-submit-bar) {
  border-radius: 1.5rem;
  background: rgba(0, 0, 0, 0.2);
}
.payBox {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  :deep(.van-popup) {
    top: 30%;
  }
  :deep(.van-number-keyboard) {
    z-index: 9999;
    bottom: 2.5rem;
  }
}
</style>
